package com.itheima.search.controller;

import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.ResultVo;
import com.itheima.search.document.ArticleInfoDocument;
import com.itheima.search.dto.SearchDto;
import com.itheima.search.service.ApAssociateWordsService;
import com.itheima.search.service.ApUserSearchService;
import com.itheima.search.service.ArticleInfoDocumentSearchService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.search.controller
 */
@RestController
@RequestMapping("/article/search")
public class SearchController {

    @Autowired
    private ArticleInfoDocumentSearchService articleInfoDocumentSearchService;

    @Autowired
    private ApUserSearchService apUserSearchService;


    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @PostMapping("/search")
    public ResultVo<List<ArticleInfoDocument>> search(@RequestBody SearchDto dto){
        List<ArticleInfoDocument> list = articleInfoDocumentSearchService.search(dto);
        // 端localStorage 仅限使用的那个端 且不能删除缓存。推荐  后端就不用写代码，由前端完成
        // 存入搜索记录到redis，则所有的使用端都可以看得到
        Long userId = Long.valueOf(RequestContextUtil.getUserId());
        if(StringUtils.isNotEmpty(dto.getSearchWords())) {
            apUserSearchService.addSearchWords(dto, userId);
        }
        return ResultVo.ok(list);
    }

}
